package com.example.wifi4server;

import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ListenerTask implements Runnable {

    public ServerSocket serverSocket;
    public int mPort;
    public Handler mHandler;

    public boolean bPause = false;
    public boolean bStop = false;


    public ArrayList<Socket> mListConnectSocket;
    public ArrayList<ReadTask> mListReadTask;
    public ArrayList<WriteTask> mListWriteTask;

    public ListenerTask(int port, Handler handler) {
        Thread.currentThread().setName("ListenerThread");
        mPort = port;
        mHandler = handler;
        try {
            serverSocket = new ServerSocket(port);//监听本机的12345端口
        } catch (IOException e) {
            e.printStackTrace();
        }

        mListConnectSocket = new ArrayList<Socket>();
        mListReadTask = new ArrayList<ReadTask>();
        mListWriteTask = new ArrayList<WriteTask>();
    }

    @Override
    public void run() {
        while (true) {
            if (bStop)
                break;
            if (serverSocket == null)
                continue;
            try {
                Socket socket = serverSocket.accept();
                Message message = Message.obtain();
                message.what = MainActivity.DEVICE_CONNECTING;
                mHandler.sendMessage(message);
                mListConnectSocket.add(socket);

                ReadTask readTask = new ReadTask(socket, mHandler);
                ThreadPoolManager.THREAD_POOL_EXECUTOR.execute(readTask);
                mListReadTask.add(readTask);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
